<template>
  <div id="userLayout">
    <div class="login_panel">
      <div class="login_panel_form">
        <div class="login_panel_form_title">
          <img
            class="login_panel_form_title_logo"
            src="@/assets/logo.png"
            alt
          />
          <p class="login_panel_form_title_p">{{ $GIN_VUE_ADMIN.appName }}</p>
        </div>
        <el-form
          ref="loginForm"
          :model="loginFormData"
          :rules="rules"
          @keyup.enter="submitForm"
        >
          <el-form-item prop="username">
            <el-input
              v-model="loginFormData.username"
              placeholder="请输入用户名"
            >
              <template #suffix>
                <span class="input-icon">
                  <el-icon>
                    <user />
                  </el-icon>
                </span>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              v-model="loginFormData.password"
              :type="lock === 'lock' ? 'password' : 'text'"
              placeholder="请输入密码"
            >
              <template #suffix>
                <span class="input-icon">
                  <el-icon>
                    <component :is="lock" @click="changeLock" />
                  </el-icon>
                </span>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="captcha">
            <div class="vPicBox">
              <el-input
                v-model="loginFormData.captcha"
                placeholder="请输入验证码"
                style="width: 60%"
              />
              <div class="vPic">
                <img
                  v-if="picPath"
                  :src="picPath"
                  alt="请输入验证码"
                  @click="loginVerify()"
                />
              </div>
            </div>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              style="width: 38%"
              size="large"
              @click="submitForm(true)"
            >
              注 册
            </el-button>
            <el-button
              type="primary"
              size="large"
              style="width: 38%; margin-left: 8%"
              @click="submitForm(false)"
            >
              登 录
            </el-button>
          </el-form-item>
        </el-form>
        <el-button
          type="primary"
          size="large"
          style="width: 38%"
          @click="dialogVisible = true"
        >
          扫脸登录
        </el-button>
      </div>
      <div class="login_panel_right"></div>
      <div class="login_panel_foot">
        <div class="links">
          <a href="http://doc.henrongyi.top/" target="_blank">
            <img src="@/assets/docs.png" class="link-icon" />
          </a>
          <a href="https://support.qq.com/product/371961" target="_blank">
            <img src="@/assets/kefu.png" class="link-icon" />
          </a>
          <a
            href="https://github.com/flipped-aurora/gin-vue-admin"
            target="_blank"
          >
            <img src="@/assets/github.png" class="link-icon" />
          </a>
          <a href="https://space.bilibili.com/322210472" target="_blank">
            <img src="@/assets/video.png" class="link-icon" />
          </a>
        </div>
        <div class="copyright">
          <BottomInfo />
        </div>
      </div>
    </div>
    <el-dialog
      v-model="dialogVisible"
      title="Tips"
      width="30%"
      :before-close="handleClose"
    >
      <el-form ref="FaceForm" :model="FaceFormData">
        <el-form-item prop="username">
          <el-input v-model="FaceFormData.username" placeholder="请输入用户名">
            <template #suffix>
              <span class="input-icon">
                <el-icon>
                  <user />
                </el-icon>
              </span>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
      <Face
        :img64str="imgstr"
        :showflag="dialogVisible"
        @getFaceImgStr="getFaceImgStr"
      />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">Cancel</el-button>
          <el-button type="primary" @click="loginByFace(FaceFormData)">
            Confirm
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Login',
}
</script>

<script setup>
import { captcha } from '@/api/user'
import { checkDB } from '@/api/initdb'
import BottomInfo from '@/view/layout/bottomInfo/bottomInfo.vue'
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/pinia/modules/user'
import Face from '@/components/face/index.vue'
const router = useRouter()

// const loginType = reactive({
//   status: false,
// })
// 验证函数
const checkUsername = (rule, value, callback) => {
  if (value.length < 5) {
    return callback(new Error('请输入正确的用户名'))
  } else {
    callback()
  }
}
const checkPassword = (rule, value, callback) => {
  if (value.length < 6) {
    return callback(new Error('请输入正确的密码'))
  } else {
    callback()
  }
}

// 获取验证码
const loginVerify = () => {
  captcha({}).then((ele) => {
    rules.captcha[1].max = ele.data.captchaLength
    rules.captcha[1].min = ele.data.captchaLength
    picPath.value = ele.data.picPath
    loginFormData.captchaId = ele.data.captchaId
  })
}
loginVerify()

// 登录相关操作
const lock = ref('lock')
const changeLock = () => {
  lock.value = lock.value === 'lock' ? 'unlock' : 'lock'
}

const loginForm = ref(null)
const picPath = ref('')
const loginFormData = reactive({
  username: 'admin',
  password: '123456',
  captcha: '',
  captchaId: '',
})
const rules = reactive({
  username: [{ validator: checkUsername, trigger: 'blur' }],
  password: [{ validator: checkPassword, trigger: 'blur' }],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    {
      message: '验证码格式不正确',
      trigger: 'blur',
    },
  ],
})

// const userStore = useUserStore()
// const login = async () => {
//   return await userStore.LoginIn(loginFormData)
// }
// const submitForm = () => {
//   loginForm.value.validate(async (v) => {
//     if (v) {
//       const flag = await login()
//       if (!flag) {
//         loginVerify()
//       }
//     } else {
//       ElMessage({
//         type: 'error',
//         message: '请正确填写登录信息',
//         showClose: true,
//       })
//       loginVerify()
//       return false
//     }
//   })
// }

// 跳转初始化
const checkInit = async () => {
  const res = await checkDB()
  if (res.code === 0) {
    if (res.data?.needInit) {
      userStore.NeedInit()
      router.push({ name: 'Init' })
    } else {
      ElMessage({
        type: 'info',
        message: '已配置数据库信息，无法初始化',
      })
    }
  }
}
const userStore = useUserStore()
const login = async () => {
  return await userStore.LoginIn(loginFormData)
}
const register = async () => {
  return await userStore.Register(loginFormData)
}
const submitForm = (loginType) => {
  loginForm.value.validate(async (v) => {
    if (v) {
      let flag
      if (loginType) {
        flag = await register()
      } else {
        flag = await login()
      }
      if (!flag) {
        loginVerify()
        loginType = false
      }
    } else {
      ElMessage({
        type: 'error',
        message: '请正确填写登录信息',
        showClose: true,
      })
      loginVerify()
      return false
    }
  })
}

// =================自定义=================
const dialogVisible = ref(false)
const imgstr = ref('')
// 将base64转换为blob
function dataURLtoFile(dataURI, type) {
  const binary = atob(dataURI.split(',')[1])
  const array = []
  for (let i = 0; i < binary.length; i++) {
    array.push(binary.charCodeAt(i))
  }
  return new Blob([new Uint8Array(array)], { type: type })
}
const FaceFormData = ref({
  username: '',
  imgstr: '',
  Facefile: undefined,
})
const getFaceImgStr = (data) => {
  console.log(
    '%c 🍷 data: ',
    'font-size:20px;background-color: #2EAFB0;color:#fff;',
    data
  )
  imgstr.value = data
  // FaceFormData.value.Facefile = base64toFile(imgstr.value)
  const blob = dataURLtoFile(imgstr.value, 'image/jpeg')
  FaceFormData.value.Facefile = new File([blob], Date.now() + '.jpg')
}

const handleClose = () => {
  imgstr.value = ''
  dialogVisible.value = false
}
const loginByFace = async () => {
  const formdata = new FormData() // new一个formdata对象
  formdata.append('Facefile', FaceFormData.value.Facefile)
  formdata.append('username', FaceFormData.value.username)
  await userStore.LoginInbyFace(formdata)
}
</script>

<style lang="scss" scoped>
@import '@/style/newLogin.scss';
</style>
